var util = require('util');

//获取配置中的websocket服务器连接地址
var websocketUrl = util.config('websocketUrl');

var requestTask = [];

let requestTimeout;

function connect(msgHandler, closeFun, errFun, callback) {
    //连接websocket服务器
    wx.connectSocket({
        url: websocketUrl,
    });
    //监听websocket打开
    wx.onSocketOpen(function() {
        //返回连接实例
        callback.success();
    });
    //监听websocket断开
    wx.onSocketClose(function() {
        closeFun();
    });
    //监听websocket连接出错
    wx.onSocketError(function(err) {
        closeFun();
        console.log(err);
        callback.fail(err);
    });
    //监听websocket消息
    wx.onSocketMessage(function(msg) {
        var data = util.isJson(msg.data);
        //判断是否json字符串，如果是则执行JSON.parse转换后再送到msgHandler
        if(data) {
            console.log(data);
            
            if(data.data && data.data.type == 'interface') {
                var pair = data.data.event || data.data.pair;
                for(var requestIndex in requestTask) {
                    if(requestTask[requestIndex].pair == pair) {
                        console.log(data.data);
                        if(data.errCode == '0') {
                            clearTimeout(requestTimeout);
                            requestTask[requestIndex].success(data.data);
                        }
                        else {
                            clearTimeout(requestTimeout);
                            requestTask[requestIndex].fail(data.errCode);
                        }
                        return;
                    }
                }
            }
            else if(data.errCode != '0') {

                callback.fail(data);

                return;

            }
            else {
                msgHandler(data);
            }
        }
        else {
            msgHandler(msg);
        }
    });
}

function request(data, callback) {
    var pair = Date.now();
    data.pair = pair;
    send(data, {
        success: function() {
            console.log('请求发送已成功等待返回值');
            requestTask.push({
                pair: pair,
                success: callback.success,
                fail: callback.fail
            });
            requestTimeout = setTimeout(function() {
                callback.fail();
            }, 10000);
        },
        fail: callback.fail
    });
}

//发送消息函数
function send(data, callback) {
    data = JSON.stringify(data);
    wx.sendSocketMessage({
        data: data,
        success: callback.success,
        fail: callback.fail
    })
}

module.exports = {
    connect: connect,
    send: send,
    request: request
};